package com.ddone.jdbc;

import com.ddone.jdbc.bean.Emp;
import com.ddone.jdbc.config.JdbcConfig;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author ddone
 * @date 2024/3/20-16:07
 */
@RunWith(SpringJUnit4ClassRunner.class)
// @ContextConfiguration(value = {"classpath:application-jdbc.xml"})
@ContextConfiguration(classes = {JdbcConfig.class})
@Slf4j
public class TestMainClass {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // getValue
    @Test
    public void testQueryString() {
        String sql = "select emp_name" +
                " from t_emp " +
                "where emp_id=?";
        String empName = jdbcTemplate.queryForObject(sql, String.class, 4);
       log.warn("emp = " + empName);
    }

    @Test
    // getList
    public void testQueryForList(){
        // 查询所有员工
        String sql = "select * from t_emp";
        List<Emp> empList = jdbcTemplate.query(sql, (resultSet, rowNum) -> {
            return Emp.builder()
                    .name(resultSet.getString("emp_name"))
                    .salary(resultSet.getDouble("emp_salary"))
                    .id(resultSet.getInt("emp_id"))
                    .build();
        });

        System.out.println("empList = " + empList);
    }

    @Test
    // getBean
    public void testQueryForOne(){
        // emp = Emp(id=4, name=王大花, salary=30000.11)
        String sql = "select emp_id,emp_name,emp_salary" +
                " from t_emp " +
                "where emp_id=?";

        RowMapper<Emp> empRowMapper = new RowMapper<Emp>() {
            @Override
            public Emp mapRow(ResultSet resultSet, int rowNum) throws SQLException {
                return Emp.builder()
                        .name(resultSet.getString("emp_name"))
                        .salary(resultSet.getDouble("emp_salary"))
                        .id(resultSet.getInt("emp_id"))
                        .build();
            }
        };

        Emp emp = jdbcTemplate.queryForObject(sql, empRowMapper, 4);
        log.warn("emp = " + emp);
    }

    @Test
    public void testUpdate(){
        String sql = "update t_emp set emp_salary=? where emp_id=?";
        int rows = jdbcTemplate.update(sql, 20000, 4);
        log.warn("rows = " + rows);
    }




}
